package com.zpy.SmartChargeStation.iotdb.service.impl;

import com.zpy.SmartChargeStation.iotdb.config.IotDBSessionConf;
import com.zpy.SmartChargeStation.iotdb.service.IoTDBService;
import jakarta.annotation.Resource;
import org.apache.iotdb.isession.pool.SessionDataSetWrapper;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.pool.SessionPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * description: iotDB Session Service实现类
 */
@Slf4j
@Service
public class IoTDBServiceImpl implements IoTDBService {

    @Resource
    private IotDBSessionConf conf;


    @Override
    public SessionDataSetWrapper executeQueryStatement(String sql) {

        SessionPool pool = conf.initSessionPool();
        SessionDataSetWrapper wrapper = null;
        try {
            wrapper=  pool.executeQueryStatement(sql);
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        }

        return wrapper;
    }

    @Override
    public SessionDataSetWrapper executeRawDataQuery(List<String> path, long startTime, long endTime, long timeOut) {
        SessionPool pool = conf.initSessionPool();
        SessionDataSetWrapper wrapper = null;
        try {
           wrapper = pool.executeRawDataQuery(path,startTime,endTime,timeOut);
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        }

        return wrapper;
    }

    @Override
    public void insertCurrentData(double current, long timestamp) {
        SessionPool pool = conf.initSessionPool();
        try {
            // 定义设备路径和测量值
            String device = "root.smart_charge_station";
            List<String> measurements = new ArrayList<>();
            measurements.add("current");

            List<String> values = new ArrayList<>();
            values.add(String.valueOf(current));

            // 插入数据到IoTDB
            pool.insertRecord(device, timestamp, measurements, values);
            log.info("成功将电流数据存储到IoTDB: current={}, timestamp={}", current, timestamp);
        } catch (IoTDBConnectionException | StatementExecutionException e) {
            log.error("存储电流数据到IoTDB时出错: ", e);
        }
    }

    public boolean Connection() {
        try {
            SessionPool pool = conf.initSessionPool();
            pool.executeNonQueryStatement("SHOW DATABASES");
            log.info("IoTDB 数据库连接成功");
            return true;
        } catch (Exception e) {
            log.error("IoTDB 数据库连接失败: ", e);
            return false;
        }
    }

}